<template>
  <view class="CreatePlanTask">
    <!-- 标题框 -->
    <view class="inputContent content">
      <text class="title">标题</text>
      <input
        type="text"
        class="inputBox"
        placeholder="请输入任务名"
        placeholder-style="font-size: 26rpx;margin-left:10rpx"
        v-model="taskContent.title"
      />
    </view>

    <!-- 任务框 -->
    <view class="taskContent content">
      <text class="title">步骤</text>
      <view class="taskBox">
        <template v-if="steps.length">
          <view class="stepBox" v-for="(item, index) in steps" :key="index">
            <input
              type="text"
              class="stepInput"
              placeholder="请输入步骤"
              placeholder-style="font-size: 26rpx;margin-left:10rpx"
              v-model="item.value"
            />
            <view @click="removeStep(index)" class="removeStep">x</view>
          </view>
        </template>
        <view class="next" @click="addTask">
          <text class="addSign">+</text>
          <text>下一步</text>
        </view>
      </view>
    </view>

    <!-- 描述框 -->
    <view class="describeContent content">
      <text class="title">描述</text>
      <view style="flex: 1">
        <MyRichTextEditor ref="myEditorRef" />
      </view>
    </view>
    <!-- 附件上传 -->
    <view class="fileContent content">
      <text class="title">附件</text>
      <view style="flex: 1">
        <MyUploader ref="myUploaderRef" :fileList="taskContent.fileList" />
      </view>
    </view>

    <!-- 选择日期框 -->
    <view class="dateContent content">
      <view class="dateBox">
        <text class="title">截止日期</text>
        <view class="dateInput">
          <image src="../../static/icons/calendar.png" class="dateIcon"></image>
          <view class="date">
            <view @click="showDateBox(0)">{{ getTime(0) }}</view>
            <view class="clear" @click="clearTime(0)">x</view>
          </view>
        </view>
      </view>
      <view class="dateBox">
        <text class="title">提醒时间</text>
        <view class="dateInput">
          <image src="../../static/icons/calendar.png" class="dateIcon"></image>
          <view class="date">
            <view @click="showDateBox(1)">{{ getTime(1) }}</view>
            <view class="clear" @click="clearTime(1)">x</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 选择日期 -->
    <van-calendar
      :show="showCalendar"
      @close="showCalendar = false"
      @confirm="confirmCalendar"
      color="#05A47D"
    />
    <!-- 选择具体时间段 -->
    <van-popup :show="showDate" position="bottom">
      <van-datetime-picker
        type="time"
        :value="getHHMM"
        :min-hour="new Date().getHours()"
        :max-hour="24"
        @confirm="confirmPickTime"
        @cancel="showDate = false"
        title="选择提醒时间"
      />
    </van-popup>

    <van-button
      block
      round
      color="#05A47D"
      class="btnSumbit"
      :disabled="btnLoading"
      @click="handleSumbit"
      >确认添加</van-button
    >
  </view>
</template>

<script>
import MyRichTextEditor from "../../components/planTask/MyRichTextEditor.vue";
import MyUploader from "../../components/planTask/MyUploader.vue";
import { mapState } from "vuex";
export default {
  name: "CreatePlanTask",
  components: {
    MyRichTextEditor,
    MyUploader,
  },
  data() {
    return {
      listId: "",
      taskContent: {
        title: "", // 任务标题
        describe: "", // 任务描述 内容
        fileList: [], // 上传附件
        steps: [], // 任务步骤
        createTime: new Date(), // 创建时间
        endTime: "", // 结束时间
        remindTime: "", // 提醒时间
        taskUser: [], //
        isFinish: false, // 是否完成
        isTime: false, // 是否截止
        allocCode: "", // 分享码
        isAlloc: "", // 是否
      },
      steps: [],
      showDate: false,
      showCalendar: false,
      btnLoading: false,
      chooseTime: "",
      timeType: 0, // 0设置截至时间 1设置具体时间日期
      dateContent: [
        {
          content: "设置日期",
          time: "",
        },
        {
          content: "设置具体时间",
          time: "",
        },
      ],
    };
  },

  onLoad: function (options) {
    this.listId = options.taskId;
  },
  computed: {
    ...mapState(["userInfo"]),
    getTime() {
      return function (index) {
        return this.dateContent[index].time.length
          ? this.dateContent[index].time
          : this.dateContent[index].content;
      };
    },
    getHHMM() {
      let hour = new Date().getHours(),
        minute = new Date().getMinutes();
      minute = minute >= 10 ? minute : "0" + minute;
      return hour + ":" + minute;
    },
  },

  methods: {
    // 获取文件上传后的详细内容
    async composeUploadFile() {
      return new Promise(async (resolve, reject) => {
        try {
          const tempFiles = this.$refs.myUploaderRef.tempFiles;
          // 没有上传列表，直接返回[]
          if (!tempFiles.length) {
            resolve([]);
          }else{
            const result = await this.$refs.myUploaderRef.uploadFileToDB();
            console.log("上传结果：", result);
            const composeFiles = tempFiles.map((item, index) => {
              return {
                author: item.author,
                fileID: result[index].fileID,
                fileName: item.name,
              };
            });
            resolve(composeFiles);
          }

        } catch (err) {
          //TODO handle the exception
          console.log("上传失败：", err);
          reject(err);
        }
      });
    },
    // 确认时间
    confirmPickTime(e) {
      console.log(e.detail);
      this.chooseTime += " " + e.detail;
      this.showDate = false;
      this.dateContent[this.timeType].time = this.chooseTime;
      if (!this.timeType) {
        this.taskContent.endTime = new Date(this.chooseTime);
      } else {
        this.taskContent.remindTime = new Date(this.chooseTime);
      }
    },

    // 确认日期
    confirmCalendar(e) {
      this.chooseTime = this.$formatTime.formatTime(e.detail);
      this.showCalendar = false;
      this.showDate = true;
    },

    // 提交信息
    async handleSumbit() {
      this.btnLoading = true;
      this.taskContent.steps = this.steps;
      const taskContent = this.taskContent,
        listId = this.listId,
        isAlloc = false;

      console.log("查看参数：", this.taskContent);
      if (this.validForm()) {
        try {
          uni.showLoading({
            title: "创建中",
          });
          const fileList = await this.composeUploadFile(); // 上传文件
          if (fileList.length) {
            this.taskContent.fileList = fileList;
          } 
          this.taskContent.describe = await this.handleGetEditorContent(); // 描述信息
          await this.$store.dispatch("m_task/addTask", {
            listId,
            taskContent,
            isAlloc,
          });
          this.$store.commit("m_task/clearTaskList"); // 重新获取数据
          await this.getTaskListData();
          uni.hideLoading();
          uni.navigateBack();
        } catch (err) {
          console.log("失败：", err);
          uni.showToast({
            icon: "error",
            title: "创建失败",
          });
        }
      }
      this.btnLoading = false;
    },

    // 获取任务列表数据
    async getTaskListData(page = 0, limitCount = 10) {
      const userId = this.userInfo._openid;
      await this.$store.dispatch("m_task/getTaskList", {
        page,
        limitCount,
        userId,
      });
    },
    // 获取富文本内容并替换为上传图片
    handleGetEditorContent() {
      return new Promise(async (resolve, reject) => {
        try {
          this.$refs.myEditorRef.getEDitContent().then(async (res) => {
            const tempPic = this.getEditorContentImg(res.html);
            const fileList = [];
            if (tempPic.length) {
              // 组合图片文件，进行上传
              tempPic.forEach((item, index) => {
                const fileName =
                  Math.floor(new Date().getTime() / 1000) + "-" + index;
                fileList.push({ fileName, filePath: item });
              });
              const uploadResult = await this.uploadEditorFile(fileList);
              // 上传至云存储将图片地址替换
              uploadResult.forEach((item, index) => {
                res.html = res.html.replace(tempPic[index], item.fileID);
              });
            }
            console.log("replace:", res.html);
            resolve(res.html);
          });
        } catch (err) {
          console.log("重置文本出错：", err);
          reject(err);
        }
      });
    },

    // 匹配出富文本内容里图片的src数组
    getEditorContentImg(html) {
      const images = html.match(/<img.*?(?:>|\/>)/gi); // 匹配出富文本里的img标签
      if (!images) {
        return [];
      }
      // 匹配出src
      let srcArr = images
        .map((str) => {
          if (!str.match(/ src=[\'\"]?([^\'\"]*)[\'\"]?/i)[1].startsWith("/")) {
            return str.match(/ src=[\'\"]?([^\'\"]*)[\'\"]?/i)[1];
          }
        })
        .filter((src) => !!src);
      return srcArr;
    },
    // 上传富文本当中的图片
    async uploadEditorFile(fileList) {
      try {
        const res = await this.$store.dispatch(
          "m_task/uploadTaskEditorImage",
          fileList
        );
        return res;
      } catch (err) {
        console.log("上传出错：", err);
      }
    },

    // 添加任务步骤
    addTask() {
      const item = {};
      item.value = "";
      item.finished = false;
      this.steps.push(item);
    },

    // 删除指定步骤
    removeStep(index) {
      this.steps.splice(index, 1);
    },

    // 打开box，同时需要设置类型
    showDateBox(type) {
      this.timeType = type;
      this.showCalendar = true;
    },

    // 清空时间内容
    clearTime(type) {
      this.dateContent[type].time = "";
      if (type) {
        this.taskContent.remindTime = "";
      } else {
        this.taskContent.endTime = "";
      }
    },

    // 验证表单信息
    validForm() {
      if (!this.taskContent.title.length) {
        uni.showToast({
          icon: "error",
          title: "标题不能为空",
        });
        return false;
      }
      if (!this.taskContent.steps.length) {
        uni.showToast({
          icon: "error",
          title: "未填写步骤",
        });
        return false;
      }
      if (!this.taskContent.endTime.toString().length) {
        uni.showToast({
          icon: "error",
          title: "截止时间未填写",
        });
        return false;
      }
      if (
        new Date(this.taskContent.endTime).getTime() <= new Date().getTime()
      ) {
        uni.showToast({
          icon: "error",
          title: "时间不符合规范",
        });
        return false;
      }
      if (
        this.taskContent.remindTime.toString().length &&
        new Date(this.taskContent.remindTime).getTime() <= new Date().getTime()
      ) {
        uni.showToast({
          icon: "error",
          title: "时间不符合规范",
        });
        return false;
      }
      if (
        this.taskContent.endTime.toString().length &&
        this.taskContent.remindTime.toString().length
      ) {
        const time1 = new Date(this.taskContent.endTime).getTime(),
          time2 = new Date(this.taskContent.remindTime).getTime();
        if (time2 >= time1) {
          uni.showToast({
            icon: "error",
            title: "时间不符合规范",
          });
          return false;
        }
      }
      return true;
    },
  },
};
</script>

<style lang="scss" scoped>
.CreatePlanTask {
  background-color: #fff;
  padding: 20rpx;
  .content {
    display: flex;
    align-items: center;
    margin: 20rpx 20rpx;
    padding-bottom: 15rpx;
    border-bottom: 1px solid #eef;
    font-size: 34rpx;
    .inputBox {
      width: 75%;
      border-radius: 8rpx;
      height: 65rpx;
      box-shadow: 0 0 5rpx rgba(0, 0, 0, 0.3);
      padding: 5rpx;
      padding-left: 15rpx;
    }
    .title {
      margin-right: 50rpx;
    }
    .next {
      color: #bbb;
      display: flex;
      align-items: center;
      .addSign {
        font-size: 45rpx;
        margin-right: 15rpx;
      }
    }

    .textBox {
      padding: 20rpx;
      width: 70%;
      height: 200rpx;
      color: #aaa;
      font-size: 30rpx;
    }
  }
  .taskContent {
    align-items: flex-start;
    .title {
      margin-top: 10rpx;
    }
    .stepBox {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      .checkBox {
        position: relative;
        width: 30rpx;
        height: 30rpx;
        border: 3rpx solid #bbb;
        border-radius: 5rpx;
        margin-right: 20rpx;
        .checkIcon {
          position: absolute;
          top: -15rpx;
          left: -6rpx;
          width: 50rpx;
          height: 55rpx;
        }
      }
      .stepInput {
        padding: 5rpx;
        padding-left: 15rpx;
        border-radius: 8rpx;
        height: 60rpx;
        box-shadow: 0 0 5rpx rgba(0, 0, 0, 0.3);
        margin-right: 20rpx;
        color: #aaa;
        font-size: 28rpx;
      }
      .removeStep {
        width: 60rpx;
        font-size: 35rpx;
        color: #bbb;
      }
    }
  }

  .describeContent,
  .fileContent {
    align-items: flex-start;
    .title {
      margin-top: 15rpx;
    }
  }

  .stepshareContent {
    .title {
      margin-right: 20rpx;
    }
    .shareBox {
      display: flex;
      align-items: center;
      .shareIcon {
        width: 60rpx;
        height: 60rpx;
      }
    }
  }

  .dateContent {
    flex-direction: column;
    align-items: flex-start;
    .title {
      margin-right: 20rpx;
    }
    .dateBox {
      display: flex;
      align-items: center;
      margin-bottom: 10rpx;
      .dateInput {
        display: flex;
        align-items: center;
        .dateIcon {
          width: 50rpx;
          height: 50rpx;
          margin-right: 10rpx;
        }
        .date {
          display: flex;
          align-items: center;
          justify-content: space-between;
          color: #999;
          font-size: 26rpx;
          width: 300rpx;
          height: 70rpx;

          .clear {
            width: 70rpx;
            font-size: 35rpx;
          }
        }
      }
    }
  }
}
</style>

<style>
page {
  background-color: #fff;
  height: 100%;
}
</style>
